package com.star.controller;

import com.star.pojo.books;
import com.star.service.bookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class bookController {

    @Autowired
    @Qualifier("bookServiceImpl")
    private bookService bookService;

    @RequestMapping("/allBook")
    public String allBook(Model model){
        List<books> books = bookService.queryAllBooks();
        model.addAttribute("books",books);
        return "allBook";
    }

    @RequestMapping("/toAddBook")
    public String toAdd(){
        return "toAddBook";
    }

    @PostMapping("/addBook")
    public String addBook(books book){
        bookService.addBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(int id,Model model){
        books book = bookService.queryBookById(id);
        model.addAttribute("book",book);
        return "toUpdateBook";
    }

    @PostMapping("/UpdateBook")
    public String UpdateBook(books book){
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/del/{bookID}")
    public String deleteBook(@PathVariable("bookID") int id){
        bookService.deleteBookByID(id);
        return "redirect:/book/allBook";
    }

    @PostMapping("/select")
    public String selectBook(String bookName,Model model){
        List<books> books = bookService.selectBook(bookName);
        if(books.size()==0){
            books = bookService.queryAllBooks();
            model.addAttribute("error","未查到！");
        }
        model.addAttribute("books",books);
        return "allBook";
    }

}
